package com.example.autooperation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.autooperation.entity.Task;
import com.example.autooperation.executor.MyTaskExecutor;
import com.example.autooperation.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/task")
public class TaskController {

    @Autowired
    private TaskService taskService;
    @Autowired
    private MyTaskExecutor myTaskExecutor;

    @GetMapping
    public Page<Task> listTasks(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int size,
                                @RequestParam(required = false) String name) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        if (name != null) {
            queryWrapper.like("name", name);
        }
        return taskService.page(new Page<>(page, size), queryWrapper);
    }

    @PostMapping
    public Task createTask(@Valid @RequestBody Task task) {
        taskService.save(task);
        return task;
    }

    @PutMapping("/{id}")
    public Task updateTask(@PathVariable int id, @Valid @RequestBody Task task) {
        task.setId(id);
        taskService.updateById(task);
        return task;
    }

    @DeleteMapping("/{id}")
    public void deleteTask(@PathVariable int id) {
        taskService.removeById(id);
    }

    @PostMapping("/{id}/start")
    public void startTask(@PathVariable int id) {
        // 启动任务的逻辑，例如更新状态，提交给执行器
        Task task = taskService.getById(id);
        task.setStatus(1); // 执行中
        taskService.updateById(task);
        myTaskExecutor.executeTask(id);
    }

    @PostMapping("/{id}/stop")
    public void stopTask(@PathVariable int id) {
        // 停止任务的逻辑
        Task task = taskService.getById(id);
        task.setStatus(4); // 已停止
        taskService.updateById(task);
        myTaskExecutor.stopTask(id);
    }

    @PostMapping("/{id}/pause")
    public void pauseTask(@PathVariable int id) {
        Task task = taskService.getById(id);
        task.setStatus(5); // 设置状态为 5（暂停）
        taskService.updateById(task);
        myTaskExecutor.pauseTask(id);
    }

    @PostMapping("/{id}/resume")
    public void resumeTask(@PathVariable int id) {
        Task task = taskService.getById(id);
        task.setStatus(1); // 设置状态为 1（执行中）
        taskService.updateById(task);
        myTaskExecutor.resumeTask(id);
    }
}